/**********************************************
 * Copyright (c) 2022
 * All rights reserved.
 *
 * 文件名称：cjson_pack.c
 * 摘 要：打包数据为cjson格式
 *
 * 当前版本：1.0
 * 作 者：任慧
 * 完成日期：2022年7月23日
 *
 * ********************************************/

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "cJSON.h"
#include "cjson_pack.h"
#include "platform.h"

int cjson_pack(struct client_data str, mqtt_t *mqtt, char *packed, int len, int platform)
{

	char s_temp[20];
	double d_temp;

	if (!mqtt || 0==len || platform<0)
	{
		return -1;
	}

	memset(s_temp, 0, sizeof(s_temp));
	snprintf(s_temp, 20, "%f",str.temp);
	d_temp = atof(s_temp);

	if (platform == ALIYUN)
	{
		cJSON *cjson = cJSON_CreateObject();
		cJSON *item = cJSON_CreateObject();

		memset(cjson, 0, sizeof(cjson));
		memset(item, 0, sizeof(item));

		cJSON_AddItemToObject(cjson, "method", cJSON_CreateString(mqtt->method));
		cJSON_AddItemToObject(cjson, "id", cJSON_CreateString(mqtt->jsonid));
		cJSON_AddItemToObject(cjson, "params", item);
		cJSON_AddItemToObject(cjson, "time", cJSON_CreateString(str.time));
		cJSON_AddItemToObject(item, "CurrentTemperature", cJSON_CreateNumber(d_temp));
		cJSON_AddItemToObject(cjson, "version", cJSON_CreateString(mqtt->version));
		strncpy(packed, cJSON_Print(cjson), len-1);

		cJSON_Delete(cjson);
	}

	if (platform == HUAWEIYUN)
	{

		cJSON *A = cJSON_CreateObject();                  
		cJSON *A1  = cJSON_CreateArray();                  
		cJSON *AA1  = cJSON_CreateObject();                  
		cJSON_AddStringToObject(AA1, "service_id", mqtt->jsonid);  
		cJSON *AA2 = cJSON_CreateObject();
		cJSON_AddNumberToObject(AA2, "CurrentTemperature", d_temp);      

		cJSON_AddItemToObject(AA1, "properties", AA2);    
		cJSON_AddStringToObject(AA1, "event_time", str.time);   
		cJSON_AddItemToObject(A1, " ", AA1);

		cJSON_AddItemToObject(A, "services", A1); 

		strncpy(packed, cJSON_Print(A), len-1);

		cJSON_Delete(A);

	}

	if (platform == TENGXUNYUN)
	{
		cJSON *cjson = cJSON_CreateObject();
		cJSON *item = cJSON_CreateObject();

		memset(cjson, 0, sizeof(cjson));
		memset(item, 0, sizeof(item));

		cJSON_AddItemToObject(cjson, "method", cJSON_CreateString(mqtt->method));
		cJSON_AddItemToObject(cjson, "clientToken", cJSON_CreateString(mqtt->jsonid));
		cJSON_AddItemToObject(cjson, "timestamp", cJSON_CreateString(str.time));
		cJSON_AddItemToObject(cjson, "params", item);
		cJSON_AddItemToObject(item, "CurrentTemperature", cJSON_CreateNumber(d_temp));
		strncpy(packed, cJSON_Print(cjson), len-1);

		cJSON_Delete(cjson);

	}
	return 0;


}
